package com.jack.helloworld.liveWallpaper;

import android.app.WallpaperManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.MediaPlayer;
import android.service.wallpaper.WallpaperService;
import android.view.SurfaceHolder;

import com.jack.helloworld.util.Constants;
import com.jack.helloworld.util.SharedPreferenceHelper;
import com.orhanobut.logger.Logger;

import java.io.File;
import java.io.IOException;

public class VideoLiveWallpaperService extends WallpaperService {

    public static VideoEngine engine;

    public Engine onCreateEngine() {
        Logger.d("VideoLiveWallpaperService#onCreateEngine:" + engine);
        return engine = new VideoEngine();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Logger.d("VideoLiveWallpaperService#onDestroy:" + engine);
//        if (engine != null) {
//            engine.resetStatus();
//        }
    }

    public static final String VIDEO_PARAMS_CONTROL_ACTION = "com.livewallpaper.videoparams";
    public static final String KEY_LIVE_WALLPAPER_ACTION = "live_wallpaper_action";
    public static final int ACTION_VOICE_SILENCE = 110;
    public static final int ACTION_VOICE_NORMAL = 111;

    public static void voiceSilence(Context context) {
        Intent intent = new Intent(VideoLiveWallpaperService.VIDEO_PARAMS_CONTROL_ACTION);
        intent.putExtra(VideoLiveWallpaperService.KEY_LIVE_WALLPAPER_ACTION, VideoLiveWallpaperService.ACTION_VOICE_SILENCE);
        context.sendBroadcast(intent);
    }

    public static void voiceNormal(Context context) {
        Intent intent = new Intent(VideoLiveWallpaperService.VIDEO_PARAMS_CONTROL_ACTION);
        intent.putExtra(VideoLiveWallpaperService.KEY_LIVE_WALLPAPER_ACTION, VideoLiveWallpaperService.ACTION_VOICE_NORMAL);
        context.sendBroadcast(intent);
    }

    public static void setToWallPaper(Context context) {
        final Intent intent = new Intent(WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER);
        intent.putExtra(WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT,
                new ComponentName(context, VideoLiveWallpaperService.class));
        context.startActivity(intent);
    }


    public class VideoEngine extends Engine {

        private MediaPlayer mMediaPlayer;

        private BroadcastReceiver mVideoParamsControlReceiver;

        @Override
        public void onCreate(SurfaceHolder surfaceHolder) {
            super.onCreate(surfaceHolder);
            Logger.d("VideoEngine#onCreate");

            IntentFilter intentFilter = new IntentFilter(VIDEO_PARAMS_CONTROL_ACTION);
            registerReceiver(mVideoParamsControlReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    Logger.d("onReceive");
                    int action = intent.getIntExtra(KEY_LIVE_WALLPAPER_ACTION, -1);

                    switch (action) {
                        case ACTION_VOICE_NORMAL:
                            mMediaPlayer.setVolume(1.0f, 1.0f);
                            break;
                        case ACTION_VOICE_SILENCE:
                            mMediaPlayer.setVolume(0, 0);
                            break;

                    }
                }
            }, intentFilter);

        }

        @Override
        public void onDestroy() {
            Logger.d("VideoEngine#onDestroy");
            unregisterReceiver(mVideoParamsControlReceiver);
            super.onDestroy();

        }

        @Override
        public void onVisibilityChanged(boolean visible) {
            Logger.d("VideoEngine#onVisibilityChanged visible = " + visible);

            if (visible) {
                Logger.d("VideoEngine#onVisibilityChanged#mMediaPlayer = " + mMediaPlayer);
                if (mMediaPlayer != null) {
                    setVoiceStatus(mMediaPlayer);
                    mMediaPlayer.start();
                }
            } else {
                if (mMediaPlayer.isPlaying()) {
                    mMediaPlayer.pause();
                }
            }

        }

        private void setVoiceStatus(MediaPlayer mediaPlayer) {
            boolean hasVoice = (Boolean) SharedPreferenceHelper.read(VideoLiveWallpaperService.this,
                    Constants.SP_LIVE_WALLPAPER,
                    Constants.SP_LIVE_WALLPAPER_KEY_VOICE,
                    SharedPreferenceHelper.BOOLEAN_VALUE);
            if (hasVoice) {
                mediaPlayer.setVolume(1.0f, 1.0f);
            } else {
                mediaPlayer.setVolume(0, 0);
            }
        }


        @Override
        public void onSurfaceCreated(SurfaceHolder holder) {
            super.onSurfaceCreated(holder);
            Logger.d("VideoEngine#onSurfaceCreated#holder: " + holder);
            initVideoLiveWallpaper(holder);
        }

        @Override
        public void onSurfaceChanged(SurfaceHolder holder, int format, int width, int height) {
            super.onSurfaceChanged(holder, format, width, height);
            Logger.d("VideoEngine#onSurfaceChanged ");
        }

        @Override
        public void onSurfaceDestroyed(SurfaceHolder holder) {
            super.onSurfaceDestroyed(holder);
            Logger.d("VideoEngine#onSurfaceDestroyed ");
            resetStatus();
        }

        public void initVideoLiveWallpaper(SurfaceHolder holder) {
            mMediaPlayer = new MediaPlayer();
            if (mMediaPlayer.isPlaying()) {
                mMediaPlayer.pause();
            }
            if (!mMediaPlayer.isPlaying()) {
                mMediaPlayer.stop();
                mMediaPlayer.reset();
            }

            Logger.d("VideoEngine#onSurfaceRedrawNeeded#holder.getSurface: " + holder.getSurface().toString());
            if (mMediaPlayer != null) {
                mMediaPlayer.setSurface(holder.getSurface());  //把视频输出到SurfaceView上
            }

            try {
                String path = (String) SharedPreferenceHelper.read(VideoLiveWallpaperService.this,
                        Constants.SP_LIVE_WALLPAPER,
                        Constants.SP_LIVE_WALLPAPER_KEY_URI,
                        SharedPreferenceHelper.STRING_VALUE);

                File file = new File(path);

                Logger.d("file.exists():" + file.exists() + ",file.isFile():" + file.isFile());
                if (file.exists() && file.isFile()) {
                    mMediaPlayer.setDataSource(path);
                } else {
                    AssetManager assetMg = getApplicationContext().getAssets();
                    AssetFileDescriptor fileDescriptor = assetMg.openFd("girl.mp4");
                    mMediaPlayer.setDataSource(fileDescriptor.getFileDescriptor(),
                            fileDescriptor.getStartOffset(), fileDescriptor.getLength());
                }
                mMediaPlayer.setLooping(true);
                setVoiceStatus(mMediaPlayer);
                // 通过异步的方式装载媒体资源
                mMediaPlayer.prepareAsync();
                mMediaPlayer.seekTo(0);
                mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mediaPlayer) {
                        // 装载完毕回调
                        mMediaPlayer.start();
                    }
                });

            } catch (IOException e) {
                Logger.e(e, "ERR:" + e.getMessage() + e.getCause());
            } catch (Exception e) {
                Logger.e(e, "ERR:" + e.getMessage() + e.getCause());
            }
        }

        public void resetStatus() {
            Logger.d("reset#mMediaPlayer: " + mMediaPlayer);
            if (mMediaPlayer != null) {
                mMediaPlayer.release();
                mMediaPlayer = null;
            }
        }

        public MediaPlayer getMediaPlayer() {
            return mMediaPlayer;
        }
    }

}